import { Link } from "react-router-dom";
import { Top } from "../components/top/Top";
import { useState, useEffect } from "react";
import "./Cart.css";
import { cartService } from "../../service/cartService";
import { common_utils } from "../../utils/utils";

export default function Cart() {
  const username = common_utils.getParamFromUrl(4);
  const [cartItems, setCartItems] = useState([]);
  const [subTotal, setSubTotal] = useState(0);
  var router = '/user/' + username + '/order';

  useEffect(() => {
    if (username) {
      cartService.getCartItems(
        username,
        (res) => {
          const items = res?.data?.cartItems;
          if (Array.isArray(items)) {
            setSubTotal(res.data.total);
            setCartItems(items);
          } else {
            console.warn("cartItems is not array:", items);
            setCartItems([]);
          }
        },
        (error) => {
          console.error("Error fetching cart items:", error);
          setCartItems([]);
        }
      );
    }
  }, [username]);

  const handleQuantityChange = (itemId, newQuantity) => {
    if (newQuantity < 1) return; // Prevent negative or zero quantities
    const updatedItems = cartItems.map(item => {
      if (item.itemId === itemId) {
        const updatedItem = { ...item, quanitity: newQuantity };
        updatedItem.totalPrice = updatedItem.listPrice * newQuantity; // Calculate new total for the item
        return updatedItem;
      }
      return item;
    });

    // Update the state with new items and recalculate subtotal
    setCartItems(updatedItems);
    const newSubTotal = updatedItems.reduce((sum, item) => sum + (item.listPrice * item.quanitity), 0);
    setSubTotal(newSubTotal);

    // Call the backend to update the quantity
    cartService.updateCartItemQuantity(username, itemId, newQuantity, (res) => {
      console.log("Quantity updated successfully:", res);
    }, (error) => {
      console.error("Error updating quantity:", error);
      // Optionally revert the state if the update fails
      cartService.getCartItems(username, (res) => {
        const items = res?.data?.cartItems;
        if (Array.isArray(items)) {
          setSubTotal(res.data.total);
          setCartItems(items);
        }
      });
    });
  };

  return (
    <>
      <Top />
      <h2>Cart</h2>
      <CartItems cartItems={cartItems} setCartItems={setCartItems} onQuantityChange={handleQuantityChange} />
      <div className="cart-footer">
        <p>Total Price: {subTotal}</p>
        <Link to={router}><button className="checkout-button">Proceed to Checkout</button></Link>
      </div>
    </>
  );
}

function CartItems({ cartItems, setCartItems, onQuantityChange }) {
  const removeItem = (item) => {
    cartService.removeCartItem(common_utils.getUsername(), item.itemId, (res) => {
      common_utils.reloadPage();
    });
  };

  return (
    <table>
      <thead>
        <tr>
          <th>Item ID</th>
          <th>Product ID</th>
          <th>Description</th>
          <th>In Stock?</th>
          <th>Quantity</th>
          <th>List Price</th>
          <th>Total Price</th>
          <th> </th>
        </tr>
      </thead>
      <tbody>
        {cartItems?.map((item) => (
          <tr key={item.itemId}>
            <td>{item.itemId}</td>
            <td>{item.productId}</td>
            <td>{item.description}</td>
            <td>{item.inStock == 1 ? "Yes" : "No"}</td>
            <td>
              <input
                type="number"
                min="1"
                value={item.quanitity}
                onChange={(e) => onQuantityChange(item.itemId, parseInt(e.target.value))}
                style={{ width: "60px" }}
              />
            </td>
            <td>{item.listPrice}</td>
            <td>{item.listPrice * item.quanitity}</td>
            <td>
              <Link to="#"><button onClick={() => removeItem(item)}>Remove</button></Link>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}